<!-- build time:Tue Dec 17 2019 19:26:43 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Spring,Spring Cloud,Hystrix,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="在微服务的架构中，服务间通常会形成相互依赖的关系，比如现在有三个微服务节点：A，B和C，B为A的消费者，C为B的消费者。假如由于网络波动或者A服务自身故障，导致B调用A服务的线程被挂起进入长时间的等待。在高并发的情况下可能导致B的资源被耗竭随之崩溃，从而导致C服务也不可用。这种连环式的雪崩效应在微服务中较为常见，为了解决这个问题，服务熔断技术应运而出。熔断一词来自电路学，指的是电路在出现短路状况时"><meta name="keywords" content="Spring,Spring Cloud,Hystrix"><meta property="og:type" content="article"><meta property="og:title" content="Spring Cloud Hystrix服务容错"><meta property="og:url" content="http://mrbird.cc/Spring-Cloud-Hystrix-Circuit-Breaker.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="在微服务的架构中，服务间通常会形成相互依赖的关系，比如现在有三个微服务节点：A，B和C，B为A的消费者，C为B的消费者。假如由于网络波动或者A服务自身故障，导致B调用A服务的线程被挂起进入长时间的等待。在高并发的情况下可能导致B的资源被耗竭随之崩溃，从而导致C服务也不可用。这种连环式的雪崩效应在微服务中较为常见，为了解决这个问题，服务熔断技术应运而出。熔断一词来自电路学，指的是电路在出现短路状况时"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180710151846.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180710154714.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180712112335.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180712173742.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180712181439.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180712185806.png"><meta property="og:image" content="http://mrbird.cc/img/QQ图片20180713111516.gif"><meta property="og:updated_time" content="2019-10-28T12:14:46.279Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Spring Cloud Hystrix服务容错"><meta name="twitter:description" content="在微服务的架构中，服务间通常会形成相互依赖的关系，比如现在有三个微服务节点：A，B和C，B为A的消费者，C为B的消费者。假如由于网络波动或者A服务自身故障，导致B调用A服务的线程被挂起进入长时间的等待。在高并发的情况下可能导致B的资源被耗竭随之崩溃，从而导致C服务也不可用。这种连环式的雪崩效应在微服务中较为常见，为了解决这个问题，服务熔断技术应运而出。熔断一词来自电路学，指的是电路在出现短路状况时"><meta name="twitter:image" content="http://mrbird.cc/img/QQ截图20180710151846.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>Spring Cloud Hystrix服务容错 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Spring-Cloud-Hystrix-Circuit-Breaker.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Spring Cloud Hystrix服务容错</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-06T08:57:40+08:00">2018-06-06 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>在微服务的架构中，服务间通常会形成相互依赖的关系，比如现在有三个微服务节点：A，B和C，B为A的消费者，C为B的消费者。假如由于网络波动或者A服务自身故障，导致B调用A服务的线程被挂起进入长时间的等待。在高并发的情况下可能导致B的资源被耗竭随之崩溃，从而导致C服务也不可用。这种连环式的雪崩效应在微服务中较为常见，为了解决这个问题，服务熔断技术应运而出。熔断一词来自电路学，指的是电路在出现短路状况时，“断路器”能够及时地切断故障电路，避免电路过载发热引发火灾。</p><p>类似的，微服务架构中的断路器能够及时地发现故障服务，并向服务调用方返回错误响应，而不是长时间的等待。Spring Cloud Hystrix在Hystrix（又是一款由Netflix开发的开源软件，Github地址<a href="https://github.com/Netflix/Hystrix" target="_blank" rel="noopener">https://github.com/Netflix/Hystrix</a>）的基础上进行了封装，提供了服务熔断，服务降级，线程隔离等功能，通过这些功能可以提供服务的容错率。<a id="more"></a></p><h2 id="使用Hystrix"><a href="#使用Hystrix" class="headerlink" title="使用Hystrix"></a>使用Hystrix</h2><p>这里将在上一节<a href="/Spring-Cloud-Ribbon-LoadBalance.html">Spring Cloud Ribbon客户端负载均衡</a>源码的基础上配置Hystrix。</p><p>我们先看下在没有配置Hystrix之前，关闭Eureka-Client是什么效果。</p><p>分别使用peer1和peer2配置启动Eureka-Server集群，然后启动两个Eureka-Client实例，端口分别为8082和8083，最后启动Ribbon-Consumer。准备完毕后，我们关闭端口为8082的Eureka-Client，然后发送GET请求<a href="http://localhost:9000/user/1" target="_blank" rel="noopener">http://localhost:9000/user/1</a>，返回结果如下：</p><p><img src="img/QQ截图20180710151846.png" alt="QQ截图20180710151846.png"></p><p>下面开始使用使用Spring Cloud Hystrix，在项目Ribbon-Consumer中引入Spring Cloud Hystrix依赖：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-hystrix<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>在入口类上加入<code>@EnableHystrix</code>或者<code>@EnableCircuitBreaker</code>注解。这两个注解是等价的，查看<code>@EnableHystrix</code>注解源码就可以证实这一点：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Inherited</span></span><br><span class="line"><span class="meta">@EnableCircuitBreaker</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> EnableHystrix &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在引入<code>@EnableHystrix</code>或者<code>@EnableCircuitBreaker</code>注解后，我们的入口类代码如下：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableCircuitBreaker</span></span><br><span class="line"><span class="meta">@EnableDiscoveryClient</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DemoApplication</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@LoadBalanced</span></span><br><span class="line">    <span class="function">RestTemplate <span class="title">restTemplate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> RestTemplate();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(DemoApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>入口类上总共包含了三个注解<code>@EnableCircuitBreaker</code>、<code>@EnableDiscoveryClient</code>和<code>@SpringBootApplication</code>，这三个注解的组合可以使用<code>@SpringCloudApplication</code>来代替，<code>@SpringCloudApplication</code>源码如下：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Inherited</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableDiscoveryClient</span></span><br><span class="line"><span class="meta">@EnableCircuitBreaker</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> SpringCloudApplication &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>接着将UserController中的方法提取出来，创建一个UserService（为了简单起见，不再创建Service接口）：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span>(<span class="string">"userService"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Logger log = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RestTemplate restTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">getUsers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.restTemplate.getForObject(<span class="string">"http://Server-Provider/user"</span>, List.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">addUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User(<span class="number">1L</span>, <span class="string">"mrbird"</span>, <span class="string">"123456"</span>);</span><br><span class="line">        HttpStatus status = <span class="keyword">this</span>.restTemplate.postForEntity(<span class="string">"http://Server-Provider/user"</span>, user, <span class="keyword">null</span>).getStatusCode();</span><br><span class="line">        <span class="keyword">if</span> (status.is2xxSuccessful()) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"新增用户成功"</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"新增用户失败"</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User(<span class="number">1L</span>, <span class="string">"mrbird"</span>, <span class="string">"123456"</span>);</span><br><span class="line">        <span class="keyword">this</span>.restTemplate.put(<span class="string">"http://Server-Provider/user"</span>, user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.restTemplate.delete(<span class="string">"http://Server-Provider/user/&#123;1&#125;"</span>, id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>接着改造UserService的<code>getUser</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserDefault</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">    user.setId(-<span class="number">1L</span>);</span><br><span class="line">    user.setUsername(<span class="string">"defaultUser"</span>);</span><br><span class="line">    user.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>我们在<code>getUser</code>方法上加入了<code>@HystrixCommand</code>注解，注解的<code>fallbackMethod</code>属性指定了被调用的方法不可用时的回调方法（服务熔断时的回调处理逻辑，即服务降级），这里为<code>getUserDefault</code>方法（必须与<code>getUser</code>方法的参数及返回值类型一致）。</p><p>在UserController中调用UserService的<code>getUser</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Logger log = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"user/&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.getUser(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>修改完后启动Ribbon-Consumer并重重新启动8082端口的Eureka-Client，发送数次GET请求<a href="http://localhost:9000/user/1" target="_blank" rel="noopener">http://localhost:9000/user/1</a>后，再次关闭8082端口的Eureka-Client。</p><p>断开后，继续发送GET请求<a href="http://localhost:9000/user/1" target="_blank" rel="noopener">http://localhost:9000/user/1</a>，当轮询到8082端口时返回数据如下图所示：</p><p><img src="img/QQ截图20180710154714.png" alt="QQ截图20180710154714.png"></p><p>可以看到，当轮询到服务不可用时，触发了熔断机制，接口回调了<code>fallbackMethod</code>指定的方法。</p><p>我们也可以模拟服务超时的情况，可以在Eureka-Client提供的接口方法中设置线程等待，等待时间大于2000（Hystrix默认超时时间为2000 毫秒）即可触发调用方Ribbon-Consumer的服务熔断。</p><h2 id="HystrixCommand详解"><a href="#HystrixCommand详解" class="headerlink" title="@HystrixCommand详解"></a>@HystrixCommand详解</h2><p><code>@HystrixCommand</code>注解还包含许多别的属性功能，下面介绍一些常用的属性配置。</p><h3 id="服务降级"><a href="#服务降级" class="headerlink" title="服务降级"></a>服务降级</h3><p>上面TestController中的<code>getUser</code>中我们用<code>@HystrixCommand</code>注解指定了服务降级方法<code>getUserDefault</code>。如果<code>getUserDefault</code>方法也抛出异常，那么我们可以再次使用<code>@HystrixCommand</code>注解指定<code>getUserDefault</code>方法降级的方法，比如定义一个<code>getUserDefault2</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault2"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserDefault</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    String a = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">// 测试服务降级</span></span><br><span class="line">    a.toString();</span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">    user.setId(-<span class="number">1L</span>);</span><br><span class="line">    user.setUsername(<span class="string">"defaultUser"</span>);</span><br><span class="line">    user.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserDefault2</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">    user.setId(-<span class="number">2L</span>);</span><br><span class="line">    user.setUsername(<span class="string">"defaultUser2"</span>);</span><br><span class="line">    user.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>重启Ribbon-Consumer，并关闭8082端口的Eureka Client服务，访问<a href="http://localhost:9000/user/1" target="_blank" rel="noopener">http://localhost:9000/user/1</a>：</p><p><img src="img/QQ截图20180712112335.png" alt="QQ截图20180712112335.png"></p><h3 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h3><p>在使用<code>@HystrixCommand</code>注解标注的方法中，除了<code>HystrixBadRequestException</code>异常外，别的异常都会触发服务降级。假如我们想指定某个异常不触发服务降级，可以使用<code>@HystrixCommand</code>注解的<code>ignoreExceptions</code>属性进行忽略。如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault2"</span>, ignoreExceptions = &#123;NullPointerException.class&#125;)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserDefault</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    String a = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">// 测试服务降级</span></span><br><span class="line">    a.toString();</span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">    user.setId(-<span class="number">1L</span>);</span><br><span class="line">    user.setUsername(<span class="string">"defaultUser"</span>);</span><br><span class="line">    user.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> HystrixBadRequestException()</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>此外，对于方法抛出的异常信息，我们可以在服务降级的方法中使用<code>Throwable</code>对象获取，如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault2"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUserDefault</span><span class="params">(Long id, Throwable e)</span> </span>&#123;</span><br><span class="line">    System.out.println(e.getMessage());</span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">    user.setId(-<span class="number">2L</span>);</span><br><span class="line">    user.setUsername(<span class="string">"defaultUser2"</span>);</span><br><span class="line">    user.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h3 id="命名与分组"><a href="#命名与分组" class="headerlink" title="命名与分组"></a>命名与分组</h3><p>通过指定<code>@HystrixCommand</code>注解的<code>commandKey</code>、<code>groupKey</code>以及<code>threadPoolKey</code>属性可以设置命令名称、分组以及线程池划分，如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault"</span>, commandKey = <span class="string">"getUserById"</span>, groupKey = <span class="string">"userGroup"</span>,</span><br><span class="line">        threadPoolKey = <span class="string">"getUserThread"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">	log.info(<span class="string">"获取用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>上面的配置指定了命令的名称为<code>getUserById</code>，组名为<code>userGroup</code>，线程池名称为<code>getUserThread</code>。</p><p>通过设置命令组，Hystrix会根据组来组织和统计命令的告警、仪表盘等信息。默认情况下，Hystrix命令通过组名来划分线程池，即组名相同的命令放到同一个线程池里，如果通过<code>threadPoolKey</code>设置了线程池名称，则按照线程池名称划分。</p><p>当<code>getUser</code>方法被调用时，日志打印如下：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2018-06-06 15:32:55.945  INFO 16192 --- [getUserThread-1] com.example.demo.Service.UserService  : 获取用户信息</span><br></pre></td></tr></table></figure><p></p><p>可看到线程名称为getUserThread-1。</p><h3 id="Hystrix缓存"><a href="#Hystrix缓存" class="headerlink" title="Hystrix缓存"></a>Hystrix缓存</h3><p>我们在Controller中调用三次<code>getUser</code>方法，参数都为1L：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"testCache"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testCache</span><span class="params">()</span></span>&#123;</span><br><span class="line">        userService.getUser(<span class="number">1L</span>);</span><br><span class="line">        userService.getUser(<span class="number">1L</span>);</span><br><span class="line">        userService.getUser(<span class="number">1L</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>当访问<a href="http://localhost:9000/testCache" target="_blank" rel="noopener">http://localhost:9000/testCache</a>时，控制台输出如下： <img src="img/QQ截图20180712173742.png" alt="QQ截图20180712173742.png"></p><p>开启缓存可以让<code>getUser</code>方法只被调用一次，剩下两次直接从缓存里获取。</p><p><strong>开启缓存</strong></p><p>要在Hystrix中开启缓存很简单，只需使用<code>@CacheResult</code>注解即可，修改UserService的<code>getUser</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheResult</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>通过上面的设定，Hystrix会将返回的User对象进行缓存，缓存的key默认为方法的所有参数，这里只有一个id参数，所以缓存的key为用户id。</p><p>这里在测试的时候遇到一个异常：</p><div class="note danger"><p>java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext? at com.netflix.hystrix.HystrixRequestCache.get(HystrixRequestCache.java:104) ~[hystrix-core-1.5.12.jar:1.5.12] at com.netflix.hystrix.AbstractCommand$7.call(AbstractCommand.java:478) ~[hystrix-core-1.5.12.jar:1.5.12] at com.netflix.hystrix.AbstractCommand$7.call(AbstractCommand.java:454) ~[hystrix-core-1.5.12.jar:1.5.12] …</p></div><p></p><p>在Hystrix的issue中找到了类似的提问：<a href="https://github.com/Netflix/Hystrix/issues/1314" target="_blank" rel="noopener">https://github.com/Netflix/Hystrix/issues/1314</a>。</p><p>大致意思是在使用Hytrix缓存之前，需要通过<code>HystrixRequestContext.initializeContext</code>初始化Hystrix请求上下文，请求结束之后需要调用<code>shutdown</code>方法关闭请求。</p><p>所以我们可以定义一个过滤器来实现这个过程：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@WebFilter</span>(filterName = <span class="string">"hystrixRequestContextServletFilter"</span>, urlPatterns = <span class="string">"/*"</span>, asyncSupported = <span class="keyword">true</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HystrixRequestContextServletFilter</span> <span class="keyword">implements</span> <span class="title">Filter</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(FilterConfig filterConfig)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">        HystrixRequestContext context = HystrixRequestContext.initializeContext();</span><br><span class="line">        filterChain.doFilter(servletRequest, servletResponse);</span><br><span class="line">        context.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><div class="note info"><p>到这里，我才意识到，其实Hystrix的缓存还是蛮鸡肋的，请求缓存不是只写入一次结果就不再变化的，而是每次请求到达Controller的时候，我们都需要为HystrixRequestContext进行初始化，之前的缓存也就是不存在了，我们是在同一个请求中保证结果相同，同一次请求中的第一次访问后对结果进行缓存，缓存的生命周期只有一次请求！</p></div><p>改造完毕后，重启项目再次访问<a href="http://localhost:9000/testCache" target="_blank" rel="noopener">http://localhost:9000/testCache</a>，控制台输出如下：</p><p><img src="img/QQ截图20180712181439.png" alt="QQ截图20180712181439.png"></p><p><strong>设定key值</strong></p><p>我们也可以明确的指定缓存的key值是什么。指定key的值有两种方式：</p><ol><li><p>通过<code>@CacheKey</code>注解指定，如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheResult</span></span><br><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault"</span>, commandKey = <span class="string">"getUserById"</span>, groupKey = <span class="string">"userGroup"</span>,</span><br><span class="line">        threadPoolKey = <span class="string">"getUserThread"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@CacheKey(<span class="string">"id"</span>)</span> @PathVariable Long id) </span>&#123;</span><br><span class="line">    log.info(<span class="string">"获取用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>也可以指定参数对象内部属性为key值：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheResult</span></span><br><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault"</span>, commandKey = <span class="string">"getUserById"</span>, groupKey = <span class="string">"userGroup"</span>,</span><br><span class="line">        threadPoolKey = <span class="string">"getUserThread"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(@CacheKey(<span class="string">"id"</span>)</span> User user) </span>&#123;</span><br><span class="line">    log.info(<span class="string">"获取用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, user.getId());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li><li><p>通过方法来指定，方法的返回值必须是String类型：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getCacheKey</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> String.valueOf(id);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@CacheResult</span>(cacheKeyMethod = <span class="string">"getCacheKey"</span>)</span><br><span class="line"><span class="meta">@HystrixCommand</span>(fallbackMethod = <span class="string">"getUserDefault"</span>, commandKey = <span class="string">"getUserById"</span>, groupKey = <span class="string">"userGroup"</span>,</span><br><span class="line">        threadPoolKey = <span class="string">"getUserThread"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">"获取用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li></ol><p>值得注意的是，方法2的优先级比方法1高。</p><p><strong>缓存清除</strong></p><p>在涉及到更新User信息的方法上，我们要及时的清除相应的缓存，否则将会导致缓存数据和实际数据不一致的问题。我们在UserService的<code>updateUser</code>方法上做缓存清除操作：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheRemove</span>(commandKey = <span class="string">"getUserById"</span>)</span><br><span class="line"><span class="meta">@HystrixCommand</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateUser</span><span class="params">(@CacheKey(<span class="string">"id"</span>)</span> User user) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.restTemplate.put(<span class="string">"http://Server-Provider/user"</span>, user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>@CacheRemove</code>的<code>commandKey</code>属性和<code>getUser</code>里定义的一致。</p><h3 id="请求合并"><a href="#请求合并" class="headerlink" title="请求合并"></a>请求合并</h3><p>请求合并就是将多个单个请求合并成一个请求，去调用服务提供者，从而降低服务提供者负载的，一种应对高并发的解决办法。</p><p>Hystrix中提供了一个<code>@HystrixCollapser</code>注解，该注解可以将处于一个很短的时间段（默认10 毫秒）内对同一依赖服务的多个请求进行整合并以批量方式发起请求。为了演示<code>@HystrixCollapser</code>注解的使用方法，我们改造下Eureka-Client（服务提供者）的UserController接口，提供一个批量处理的方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"user"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Logger log = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"users"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">get</span><span class="params">(String ids)</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">"批量获取用户信息"</span>);</span><br><span class="line">        List&lt;User&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (String id : ids.split(<span class="string">","</span>)) &#123;</span><br><span class="line">            list.add(<span class="keyword">new</span> User(Long.valueOf(id), <span class="string">"user"</span> + id, <span class="string">"123456"</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>然后在Ribbon-Consumer的UserService里添加两个方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@HystrixCollapser</span>(batchMethod = <span class="string">"findUserBatch"</span>, collapserProperties = &#123;</span><br><span class="line">        <span class="meta">@HystrixProperty</span>(name = <span class="string">"timerDelayInMilliseconds"</span>, value = <span class="string">"100"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Future&lt;User&gt; <span class="title">findUser</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">"获取单个用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> AsyncResult&lt;User&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> User <span class="title">invoke</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> restTemplate.getForObject(<span class="string">"http://Server-Provider/user/&#123;id&#125;"</span>, User.class, id);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@HystrixCommand</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findUserBatch</span><span class="params">(List&lt;Long&gt; ids)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">"批量获取用户信息,ids: "</span> + ids);</span><br><span class="line">    User[] users = restTemplate.getForObject(<span class="string">"http://Server-Provider/user/users?ids=&#123;1&#125;"</span>, User[].class, StringUtils.join(ids, <span class="string">","</span>));</span><br><span class="line">    <span class="keyword">return</span> Arrays.asList(users);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>@HystrixCollapser</code>注解的<code>batchMethod</code>属性指定了批量处理的方法为下面定义的<code>findUserBatch</code>方法，<code>timerDelayInMilliseconds</code>的值为100（毫秒），意思是在100毫秒这个时间范围内的所有对<code>findUser</code>的调用，都将被合并为一个批量处理操作，进行批量处理操作的方法就是<code>findUserBatch</code>。</p><p>我们在TestController中添加一个测试方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(<span class="string">"testRequestMerge"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testRequerstMerge</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, ExecutionException </span>&#123;</span><br><span class="line">    Future&lt;User&gt; f1 = userService.findUser(<span class="number">1L</span>);</span><br><span class="line">    Future&lt;User&gt; f2 = userService.findUser(<span class="number">2L</span>);</span><br><span class="line">    Future&lt;User&gt; f3 = userService.findUser(<span class="number">3L</span>);</span><br><span class="line">    f1.get();</span><br><span class="line">    f2.get();</span><br><span class="line">    f3.get();</span><br><span class="line">    Thread.sleep(<span class="number">200</span>);</span><br><span class="line">    Future&lt;User&gt; f4 = userService.findUser(<span class="number">4L</span>);</span><br><span class="line">    f4.get();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>上面的测试方法中对<code>findUser</code>方法进行了4次的调用，最后一次调用（f4）之前先让线程等待200毫秒（大于<code>timerDelayInMilliseconds</code>中定义的100毫秒），所以我们的预期是前三次调用会被合并，而最后一次调用不会被合并进去。</p><p>启动Ribbon-Consumer，访问<a href="http://localhost:9000/testRequestMerge" target="_blank" rel="noopener">http://localhost:9000/testRequestMerge</a>,控制台输出如下：</p><p><img src="img/QQ截图20180712185806.png" alt="QQ截图20180712185806.png"></p><p>可以看到，控制台的输出符合我们的预期，f1、f2和f3被合并成了一个请求。</p><p>而且可以看到，控制台并没有打印出<code>findUser</code>方法中的<code>获取单个用户信息</code>的日志，实际上<code>findUser</code>方法并不会被调用，所以上面的代码可以简化为：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@HystrixCollapser</span>(batchMethod = <span class="string">"findUserBatch"</span>, collapserProperties = &#123;</span><br><span class="line">        <span class="meta">@HystrixProperty</span>(name = <span class="string">"timerDelayInMilliseconds"</span>, value = <span class="string">"100"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Future&lt;User&gt; <span class="title">findUser</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">"获取单个用户信息"</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@HystrixCommand</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findUserBatch</span><span class="params">(List&lt;Long&gt; ids)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">"批量获取用户信息,ids: "</span> + ids);</span><br><span class="line">    User[] users = restTemplate.getForObject(<span class="string">"http://Server-Provider/user/users?ids=&#123;1&#125;"</span>, User[].class, StringUtils.join(ids, <span class="string">","</span>));</span><br><span class="line">    <span class="keyword">return</span> Arrays.asList(users);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>虽然通过请求的合并可以减轻带宽和服务的压力，但合并请求的过程也会带来额外的开销。就拿上面的<code>testCache</code>来说，比如我们对单个<code>findUser</code>的方法调用耗时5ms，那么调用4次耗时可以粗略的估算为20ms。当我们使用Hystrix的请求合并功能后，前3次请求（f1、f2和f3）进行了合并，第4次请求（f4）没有进行合并，那么耗时可以粗略的估算为<code>3*5+100+5=120ms</code>（100为上面<code>timerDelayInMilliseconds</code>中指定的时间范围，在该时间段过后，才会调用第4次请求），结果明显比单独调用4次来得高。所以实际中是否该使用Hystrix的请求合并功能，需结合实际需求进行抉择。</p><h2 id="Hystrix属性"><a href="#Hystrix属性" class="headerlink" title="Hystrix属性"></a>Hystrix属性</h2><p>除了上面涉及到的Hystrix属性配置外，其还包含了大量的别的可用配置。配置可以分为四个级别，优先级从低到高分别为：全局默认配置、全局配置、实例默认值、实例配置。</p><h3 id="Commond"><a href="#Commond" class="headerlink" title="Commond"></a>Commond</h3><h4 id="execution"><a href="#execution" class="headerlink" title="execution"></a>execution</h4><p><code>execution.isolation.strategy</code>： 该属性用来设置执行的隔离策略，它有如下两个选项。</p><ol><li><p><code>THREAD</code>: 通过线程池隔离的策略。它在独立的线程上执行， 并且它的并发限制受线程池中线程数量的限制。</p></li><li><p><code>SEMAPHORE</code>: 通过信号量隔离的策略。它在调用线程上执行， 并且它的并发限制受信号量计数的限制。</p></li></ol><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>THREAD</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.isolation.strategy</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.isolation.strategy”, value=”THREAD”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.isolation.strategy</td></tr></table><div class="note info"><p>实例配置中的HystrixCommandKey对应@HystrixCommand注解中commandKey 属性指定的值。</p></div><p><code>execution.isolation.thread.timeoutinMilliseconds</code>： 该属性用来配置HystrixCommand执行的超时时间，单位为毫秒。当HystrixCommand执行时间超过该配置值之后， Hystrix会将该执行命令标记为TIMEOUT并进入服务降级处理逻辑。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>1000亳秒</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.isolation.thread. timeoutinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.isolation.thread.timeoutinMilliseconds”,value=”2000”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.isolation.thread.timeoutinMilliseconds</td></tr></table><p><code>execution.timeout.enabled</code>: 该属性用来配置HystrixCommand的执行是否启用超时时间。默认为true, 如果设置为false, 那么<code>execution.isolation.thread.timeoutinMilliseconds</code>属性的配置将不再起作用。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.timeout.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.timeout.enabled”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.timeout.enabled</td></tr></table><p><code>execution.isolation.thread.interruptOnTimeout</code>: 该属性用来配置当HystrixCommand执行超时的时候是否要将它中断。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.isolation.thread.interruptOnTimeout</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.isolation.thread.interruptOnTimeout”,value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnTimeout</td></tr></table><p><code>execution.isolation.thread.interruptOnCancel</code>: 该属性用来配置当HystrixCommand执行被取消的时候是否要将它中断。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.isolation.thread.interruptOnCancel</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.isolation.thread.interruptOnCancel”,value= “false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnCancel</td></tr></table><p><code>execution.isolation.semaphore.maxConcurrentRequests</code>: 当HystrixCommand的隔离策略使用信号量的时候，该属性用来配置信号量的大小（并发请求数）。当最大并发请求数达到该设置值时，后续的请求将会被拒绝。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>10</td></tr><tr><td>全局配置</td><td>hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”execution.isolation.semaphore.maxConcurrentRequests”, value=”2”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.execution.isolation.semaphore.maxConcurrentRequests</td></tr></table><h4 id="fallback"><a href="#fallback" class="headerlink" title="fallback"></a>fallback</h4><p><code>fallback.enabled</code>: 该属性用来设置服务降级策略是否启用，如果设置为false,那么当请求失败或者拒绝发生时，将不会调用降级服务。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.fallback.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name= “fallback.enabled”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.fallback.enabled</td></tr></table><h4 id="circuitBreaker断路器"><a href="#circuitBreaker断路器" class="headerlink" title="circuitBreaker断路器"></a>circuitBreaker断路器</h4><p><code>circuitBreaker.enabled</code>: 该属性用来确定当服务请求命令失败时， 是否使用断路器来跟踪其健康指标和熔断请求。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”circutBreaker.enabled”,value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.circuitBreaker.enabled</td></tr></table><p><code>circuitBreaker.requestVolumeThreshold</code>: 该属性用来设置在滚动时间窗中，断路器熔断的最小请求数。例如，默认该值为20 的时候，如果滚动时间窗（默认10秒）内仅收到了19个请求， 即使这19个请求都失败了，断路器也不会打开。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>20</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.requestVolumeThreshold</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”circuitBreaker.requestVolumeThreshold”, value=”30”)</td></tr><tr><td>实例配置</td><td>hystrix.comrnand.HystrixComrnandKey.circuitBreaker.requestVolumeThreshold</td></tr></table><p><code>circuitBreaker.sleepWindowinMilliseconds</code>: 该属性用来设置当断路器打开之后的休眠时间窗。休眠时间窗结束之后，会将断路器置为“半开” 状态， 尝试熔断的请求命令，如果依然失败就将断路器继续设置为“打开” 状态，如果成功就设置为“关闭” 状态。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>5000</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.sleepWindowinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”circuitBreaker.sleepWindowinMilliseconds”,value=”3000”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.circuitBreaker.sleepWindowinMilliseconds</td></tr></table><p><code>circuitBreaker.errorThresholdPercentage</code>: 该属性用来设置断路器打开的错误百分比条件。例如，默认值为5000 的情况下，表示在滚动时间窗中，在请求数量超过<code>circuitBreaker.requestVolumeThreshold</code>阅值的前提下，如果错误请求数的百分比超过50, 就把断路器设置为“打开” 状态， 否则就设置为“关闭” 状态。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>50</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.errorThresholdPercentage</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”circuitBreaker.errorThresholdPercentage”, value=”40”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.circuitBreaker.errorThresholdPercentage</td></tr></table><p><code>circuitBreaker.forceOpen</code>: 如果将该属性设置为true, 断路器将强制进入“打开” 状态，它会拒绝所有请求。该属性优先于<code>circuitBreaker.forceClosed</code>属性。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>false</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.forceOpen</td></tr><tr><td>实例默认值</td><td>@HystrixProperty (name=”circuitBreaker.forceOpen”, value=”true”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen</td></tr></table><p><code>circuitBreaker.forceClosed</code>: 如果将该属性设置为true, 断路器将强制进入“关闭” 状态， 它会接收所有请求。如果<code>circuitBreaker.forceOpen</code>属性为true, 该属性不会生效。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>false</td></tr><tr><td>全局配置</td><td>hystrix.command.default.circuitBreaker.forceClosed</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”circui七Breaker.forceClosed”, value=”true”)</td></tr><tr><td>实例配置</td><td>hystrix.comrnand.HystrixComrnandKey.circuitBreaker.forceClosed</td></tr></table><h4 id="metrics配置"><a href="#metrics配置" class="headerlink" title="metrics配置"></a>metrics配置</h4><p>该配置与HystrixCommand执行中捕获的指标信息有关。</p><p><code>metrics.rollingStats.timeinMilliseconds</code>: 该属性用来设置滚动时间窗的长度， 单位为毫秒。该时间用于断路器判断健康度时需要收集信息的持续时间。断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个“桶” 来累计各度量值，每个“桶” 记录了一段时间内的采集指标。例如，当采用默认值10000毫秒时， 断路器默认将其拆分成10个桶（桶的数量也可通过<code>metrics.rollingStats.numBuckets</code>参数设置），每个桶记录1000毫秒内的指标信息。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>10000</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingStats.timeinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingStats.timeinMilliseconds”,value=”20000”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.rollingStats.timeinMilliseconds</td></tr></table><p><code>metrics.rollingstats.numBuckets</code>: 该属性用来设置滚动时间窗统计指标信息时划分“桶” 的数量。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>10</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingStats.numBuckets</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingStats.numBuckets”,value=”20”)</td></tr><tr><td>实例配置</td><td>hystrix.comrnand.HystrixComrnandKey.metrics.rollingStats.numBuckets</td></tr></table><p><code>metrics.rollingPercentile.enabled</code>: 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为false，那么所有的概要统计都将返回-1。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingPercentile.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingPercentile.enabled”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.rollingPercentile.enabled</td></tr></table><p><code>metrics.rollingPercentile.timeinMilliseconds</code>: 该属性用来设置百分位统计的滚动窗口的持续时间，单位为毫秒。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>60000</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingPercentile.timeinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingPercentile.timeinMilliseconds”, value=”50000”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.rollingPercentile.timeinMilliseconds</td></tr></table><p><code>metrics.rollingPercentile.numBuckets</code>: 该属性用来设置百分位统计滚动窗口中使用“桶”的数量。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>6</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingPercentile.numBuckets</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingPercentilee.numBuckets”,value=”5”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.rollingPercentile.numBuckets</td></tr></table><p><code>metrics.rollingPercentile.bucketSize</code>: 该属性用来设置在执行过程中每个“桶” 中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数，就从最初的位置开始重写。例如，将该值设置为100, 滚动窗口为10秒，若在10秒内一个“桶”中发生了500次执行，那么该“桶”中只保留最后的100次执行的统计。另外，增加该值的大小将会增加内存量的消耗，并增加排序百分位数所需的计算时间。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>100</td></tr><tr><td>全局配置</td><td>hystrix.command.default.metrics.rollingPercentile.bucketSize</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.rollingPercentile.bucketSize”,value= “120”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.rollingPercentile.bucketSize</td></tr></table><p><code>metrics.healthSnapshot.intervalinMilliseconds</code>: 该属性用来设置采集影响断路器状态的健康快照（请求的成功、错误百分比）的间隔等待时间。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>500</td></tr><tr><td>全局配置</td><td>hystrix.comrnand.default.metrics.healthSnapshot.intervalinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”metrics.healthSnapshot.intervalinMilliseconds”,value=”600”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.metrics.healthSnapshot.intervalinMilliseconds</td></tr></table><h4 id="requestContext"><a href="#requestContext" class="headerlink" title="requestContext"></a>requestContext</h4><p><code>requestCache.enabled</code>: 此属性用来配置是否开启请求缓存。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.command.default.requestCache.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”requestCache.enabled”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.command.HystrixCommandKey.requestCache.enabled</td></tr></table><h3 id="collapser"><a href="#collapser" class="headerlink" title="collapser"></a>collapser</h3><p><code>maxRequestsinBatch</code>: 该参数用来设置一次请求合并批处理中允许的最大请求数。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>Integer.MAX_VALUE</td></tr><tr><td>全局配置</td><td>hystrix.collapser.default.maxRequestsinBatch</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”maxRequestsinBatch”,value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.collapser.HystrixCollapserKey.maxRequestsinBatch</td></tr></table><p><code>timerDelayinMilliseconds</code>: 该参数用来设置批处理过程中每个命令延迟的时间，单位为毫秒。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>10</td></tr><tr><td>全局配置</td><td>hystrix.collapser.default.timerDelayinMilliseconds</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”timerDelayinMilliseconds”,value=”20”)</td></tr><tr><td>实例配置</td><td>hystrix.collapser.HystrixCollapserKey.timerDelayinMilliseconds</td></tr></table><p><code>request Cache.enabled</code>: 该参数用来设置批处理过程中是否开启请求缓存。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>true</td></tr><tr><td>全局配置</td><td>hystrix.collapser.default.requestCache.enabled</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”requestCache.enabled”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.collapser.HystrixCollapserKey.requestCache.enabled</td></tr></table><h3 id="threadPool"><a href="#threadPool" class="headerlink" title="threadPool"></a>threadPool</h3><p><code>coreSize</code>: 该参数用来设置执行命令线程池的核心线程数，该值也就是命令执行的最大并发量。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>10</td></tr><tr><td>全局配置</td><td>hystrix.threadpool.default.coreSize</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”coreSize”, value=”false”)</td></tr><tr><td>实例配置</td><td>hystrix.threadpool.HystrixThreadPoolKey.coreSize</td></tr></table><p><code>maxQueueSize</code>: 该参数用来设置线程池的最大队列大小。当设置为-1时，线程池将使用<code>SynchronousQueue</code>实现的队列，否则将使用<code>LinkedBlockingQueue</code>实现的队列。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>-1</td></tr><tr><td>全局配置</td><td>hystrix.threadpool.default.maxQueueSize</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”maxQueueSize”,value=”lO”)</td></tr><tr><td>实例配置</td><td>hystrix.threadpool.HystrixThreadPoolKey.maxQueueSize</td></tr></table><p><code>queueSizeRejectionThreshold</code>: 该参数用来为队列设置拒绝阈值。通过该参数，即使队列没有达到最大值也能拒绝请求。该参数主要是对<code>LinkedBlockingQueue</code>队列的补充， 因为<code>LinkedBlockingQueue</code>队列不能动态修改它的对象大小，而通过该属性就可以调整拒绝请求的队列大小了。</p><table><tr><th>属性级别</th><th>默认值、配置方式、配置属性</th></tr><tr><td>全局默认配置</td><td>5</td></tr><tr><td>全局配置</td><td>hystrix.threadpool.default.queueSizeRejectionThreshold</td></tr><tr><td>实例默认值</td><td>@HystrixProperty(name=”queueSizeRejectionThreshold”, value=”lO”</td></tr><tr><td>实例配置</td><td>hystrix.threadpool.HystrixThreadPoolKey.queueSizeRejectionThreshold</td></tr></table><p>不得不说，配置是真的多……</p><p><img src="img/QQ图片20180713111516.gif" alt="QQ图片20180713111516.gif"></p><p>源码链接：<a href="https://github.com/wuyouzhuguli/Spring-Boot-Demos/tree/master/30.Spring-Cloud-Hystrix-Circuit-Breaker" target="_blank" rel="noopener">https://github.com/wuyouzhuguli/Spring-Boot-Demos/tree/master/30.Spring-Cloud-Hystrix-Circuit-Breaker</a></p><blockquote><p>参考文章 <a href="https://book.douban.com/subject/27025912/" target="_blank" rel="noopener">《Spring Cloud微服务实战》</a></p></blockquote><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Spring-Cloud-Hystrix-Circuit-Breaker.html" title="Spring Cloud Hystrix服务容错">http://mrbird.cc/Spring-Cloud-Hystrix-Circuit-Breaker.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Spring/" rel="tag"># Spring</a> <a href="/tags/Spring-Cloud/" rel="tag"># Spring Cloud</a> <a href="/tags/Hystrix/" rel="tag"># Hystrix</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Spring-Cloud-Ribbon-LoadBalance.html" rel="next" title="Spring Cloud Ribbon客户端负载均衡"><i class="fa fa-chevron-left"></i> Spring Cloud Ribbon客户端负载均衡</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Spring-Cloud-Hystrix-Dashboard.html" rel="prev" title="Spring Cloud Hystrix Dashboard仪表盘">Spring Cloud Hystrix Dashboard仪表盘 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Hystrix"><span class="nav-number">1.</span> <span class="nav-text">使用Hystrix</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HystrixCommand详解"><span class="nav-number">2.</span> <span class="nav-text">@HystrixCommand详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务降级"><span class="nav-number">2.1.</span> <span class="nav-text">服务降级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异常处理"><span class="nav-number">2.2.</span> <span class="nav-text">异常处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#命名与分组"><span class="nav-number">2.3.</span> <span class="nav-text">命名与分组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hystrix缓存"><span class="nav-number">2.4.</span> <span class="nav-text">Hystrix缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#请求合并"><span class="nav-number">2.5.</span> <span class="nav-text">请求合并</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hystrix属性"><span class="nav-number">3.</span> <span class="nav-text">Hystrix属性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Commond"><span class="nav-number">3.1.</span> <span class="nav-text">Commond</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#execution"><span class="nav-number">3.1.1.</span> <span class="nav-text">execution</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#fallback"><span class="nav-number">3.1.2.</span> <span class="nav-text">fallback</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#circuitBreaker断路器"><span class="nav-number">3.1.3.</span> <span class="nav-text">circuitBreaker断路器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#metrics配置"><span class="nav-number">3.1.4.</span> <span class="nav-text">metrics配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#requestContext"><span class="nav-number">3.1.5.</span> <span class="nav-text">requestContext</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#collapser"><span class="nav-number">3.2.</span> <span class="nav-text">collapser</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#threadPool"><span class="nav-number">3.3.</span> <span class="nav-text">threadPool</span></a></li></ol></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->